package com.nacos.common.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.nacos.common.entity.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Component
 */
@Component
public class JWTUtils {
    @Value("${token.sign:!DJFONRGOEWH324gdt&&&87uj!@%%$&#Jmm}")
    private String sing = "!DJFONRGOEWH324gdt&&&87uj!@%%$&#Jmm";
    @Value("${token.tokenExpiresTime:120}")
    private int tokenExpiresTime = 100;

    /**
     * 根据请求参数生成token信息
     */
    public String getToken(Map<String, String> paramsMap) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, tokenExpiresTime);
        JWTCreator.Builder builder = JWT.create();
        paramsMap.forEach(((k, v) -> {

            builder.withClaim(k, v);
        }));
        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(sing)
                );
        return token;
    }

    /**
     * 旧token，置换新token
     */
    public String getreFreshToken(String token) throws JWTVerificationException {
        try {
            Map<String, Claim> tokenInfo = JWT.decode(token).getClaims();
            Map<String, String> newMap = new HashMap<>();
            tokenInfo.forEach((k, v) -> {
                newMap.put(k, v.asString());
            });
            return getToken(newMap);
        } catch (JWTVerificationException e) {
            throw e;
        }
    }

    /**
     * 验证token合法性
     */
    public void verify(String token) throws JWTVerificationException {
        try {
            JWT.require(Algorithm.HMAC256(sing)).build().verify(token);
        } catch (JWTVerificationException e) {
            throw e;
        }
    }

    /**
     * 获取过期时间
     */
    public Date getTokenExp(String token) {
        Date date =  JWT.decode(token).getClaim("exp").asDate();
        return date;
    }

//    public static void main(String[] args) {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
//        JWTUtils jwtUtils = new JWTUtils();
//        User user = new User();
//        user.setId("123");
//        user.setPassword("aaa");
//        user.setUsername("test");
//        String token = jwtUtils.getToken(JSON.parseObject(JSON.toJSONString(user), Map.class));
//        try {
//            jwtUtils.verify(token);
//            System.out.println("验证成功");
//        } catch (Exception e) {
//            System.out.println("验证失败");
//        }
//
//
//        //刷新token
//        String newToken = jwtUtils.getreFreshToken(token);
//        try {
//            jwtUtils.verify(newToken);
//            System.out.println("验证成功");
//        } catch (Exception e) {
//            System.out.println("验证失败");
//        }
//        Date date =  JWT.decode(token).getClaim("exp").asDate();
//
//        System.out.println(date);
//        System.out.println(new Date());
//
//    }

}
